#!/usr/bin/python3

# coding=utf-8


# Created: 2020-02-20
# Updated: 2021-04-25
# Author : comet
# Description: scan bluetooth devices and get info.

from bluepy.btle import Scanner, DefaultDelegate
import requests
import uuid
import socket
import json

app_version = "1.0"
loc = 'HackerSpace'
url = 'https://www.ictspark.com/iot/bluetooth/iot_receive.php'
token = 'iotofict'


def get_mac_address(): 
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return "".join([mac[e:e+2] for e in range(0, 11, 2)])


def get_local_ip():
    local_ip = ""
    try:
        socket_objs = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
        ip_from_ip_port = [(s.connect(("114.114.114.114", 53)), s.getsockname()[0], s.close()) for s in socket_objs][0][1]
        ip_from_host_name = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1]
        local_ip = [l for l in (ip_from_ip_port, ip_from_host_name) if l][0]
    except (Exception) as e:
        print("get_local_ip found exception : %s" % e)
    return local_ip if("" != local_ip and None != local_ip) else socket.gethostbyname(socket.gethostname())


class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print("Discovered device", dev.addr)
        elif isNewData:
            print("Received new data from", dev.addr)

scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(10.0)

# get local mac
mymac = get_mac_address()
# get hostname
myname = socket.getfqdn(socket.gethostname())
# get local ip
myaddr = get_local_ip()


for dev in devices:
    bt_atts = ""
    bt_fields = ""
    url_headers = {'Content-Type': 'application/json'}
    print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
    if dev.addr is not None:
        bt_fields = '{"ac":"'+token+'","ver":"'+app_version+'","hostMac":"'+mymac.upper()+'","guestMac":"'+dev.addr+ \
                    '","addrType":"'+dev.addrType+'","rssi":"'+str(dev.rssi)+'",'
        for (adtype, desc, value) in dev.getScanData():
            bt_fields += '"%s":"%s",' % (desc, value)
        # 去掉最后一个逗号
        bt_fields = bt_fields[:-1]+'}'
        # 以json方式提交
        response = requests.post(url, headers=url_headers, data=json.dumps(bt_fields))
        # 对中文信息进行解码
        res_str = response.content.decode('unicode_escape')
        print(res_str)
        # print(bt_fields)
    else:
        print('Failed to get reading. Try again!')
        sys.exit(1)

